const router = require('express').Router()
// npm i -S md5
const md5 = require('md5')
const {query} = require('../db')

// 检查账号是否已经在对应的数据表中存在
router.post('/checkuser', async (req, res) => {
  let {username} = req.body
  // 现在我所写的sql，它其实是不太安全的，有xss风险，但是对于mock数据来说，可以用的
  const sql = `select * from users where username='${username}'`
  let ret = await query(sql)
  if (ret.length > 0) {
    res.send({
      code: 1,
      msg: '已存在',
      data: ret[0]
    })
  } else {
    res.send({
      code: 0,
      msg: 'ok',
      data: {}
    })
  }
})

// 添加用户
router.post('/user', async (req, res) => {
  let {username, nickname, password, role} = req.body
  // 对于密码进行密码
  password = md5(password)
  // 添加的sql语句
  const sql = `insert into users (username, nickname,password, role) 
  values ('${username}','${nickname}','${password}',${role})`
  const ret = await query(sql)
  res.send({
    code: 0,
    msg: 'ok',
    data: {username}
  })
})


// 获取用户列表
router.get('/user', async (req, res) => {

  const {page = 1} = req.query
  const pagesize = 10
  const offset = (page - 1) * pagesize
  // 表关联查询
  let sql = `select a.id,username,role,b.showname from users as a,roles as b where a.role=b.id order by a.id desc limit ${offset},${pagesize}`
  let outData = await query(sql)
  res.send({
    code: 0,
    msg: 'ok',
    data: outData
  })
})

module.exports = router
